//
//  BatchService.swift
//  redbox
//
//  Created by ma c on 2025/9/11.
//

import Foundation

class BatchService {
    static let shared = BatchService()
    
    private init() {}
    
    /// 批量领取指定活动
    func claimActivity(_ activity: Activity, for boxes: [Box], progress: @escaping (Box, String) -> Void, completion: @escaping () -> Void) {
        let group = DispatchGroup()
        
        for box in boxes {
            group.enter()
            
            // 模拟领取操作（实际应该使用WebView执行）
            DispatchQueue.global().asyncAfter(deadline: .now() + Double.random(in: 1...3)) {
                let results = ["成功", "失败", "已领取"]
                let result = results.randomElement() ?? "未知"
                
                DispatchQueue.main.async {
                    progress(box, result)
                    group.leave()
                }
            }
        }
        
        group.notify(queue: .main) {
            completion()
        }
    }
    
    /// 批量领取多个活动
    func claimActivities(_ activities: [Activity], for boxes: [Box], progress: @escaping (Box, Activity, String) -> Void, completion: @escaping () -> Void) {
        let group = DispatchGroup()
        
        for activity in activities {
            for box in boxes {
                group.enter()
                
                // 模拟领取操作
                DispatchQueue.global().asyncAfter(deadline: .now() + Double.random(in: 2...5)) {
                    let results = ["成功", "失败", "已领取", "网络超时"]
                    let result = results.randomElement() ?? "未知"
                    
                    DispatchQueue.main.async {
                        progress(box, activity, result)
                        group.leave()
                    }
                }
            }
        }
        
        group.notify(queue: .main) {
            completion()
        }
    }
    
    /// 获取批量操作统计
    func getBatchStatistics() -> BatchStatistics {
        // 模拟统计数据
        return BatchStatistics(
            totalClaims: 152,
            successRate: 0.85,
            averageTime: 2.5,
            lastRun: Date().addingTimeInterval(-3600)
        )
    }
}

// 批量操作统计
struct BatchStatistics {
    let totalClaims: Int
    let successRate: Double
    let averageTime: Double
    let lastRun: Date
    
    var successRateString: String {
        "\(Int(successRate * 100))%"
    }
    
    var averageTimeString: String {
        "\(averageTime)s"
    }
}